<?php

namespace App\Models\fund;

use App\Common\statement\CommonStatement;
use App\Models\base\traits\HasOwner;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\fund\Voucher
 *
 * @property int $id
 * @property int $user_id 关联用户ID
 * @property string $code 券码
 * @property string $title 服务券说明
 * @property int $amount 金额
 * @property int $status 服务券状态  1 => 待使用  2=>已核销
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read mixed $status_text
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereUserId($value)
 * @mixin \Eloquent
 * @property-read \App\Models\User $user
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher owner($userId)
 * @property string|null $end_at 到期时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\fund\Voucher whereEndAt($value)
 */
class Voucher extends Model
{

    use HasOwner;

    protected $fillable = [
        'amount',
        'code',
        'title',
        'user_id',
        'status',
        'end_at'
    ];

    protected $appends = [
        'status_text'
    ];


    public function getStatusAttribute($value)
    {
        if ($this->end_at < Carbon::now() && $value == 1){
            $this->status = 0;
            $this->save();
            return 0;
        }
        return $value;
    }

    public function getStatusTextAttribute()
    {

        if ($this->end_at < Carbon::now() && $this->status == 1){
            return '已过期';
        }

        return CommonStatement::voucher_status[$this->status];

    }


}
